package edu.cs346.group5.ui.userpages;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JTable;
import javax.swing.JLabel;

import edu.cs346.group5.backend.Database;
import edu.cs346.group5.datastores.Topic;
import edu.cs346.group5.datastores.WHTopic;
import edu.cs346.group5.logic.Home;
import edu.cs346.group5.logic.Login;
import edu.cs346.group5.ui.MenuFactory;
import edu.cs346.group5.ui.forumpages.view_topic;

public class home extends JFrame {

	final int MOST_RECENT = 1;
	final int HIGH_RATED = 2;
	final int USER_POSTED_CAT = 3;
	final int MOST_COMMENTS = 4;

	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JTable table;
	private JTable table_1;
	private Object[][] allTopicsTableObjects;

	/**
	 * Launch the application.
	 */

	/**
	 * Create the frame.
	 */
	public home() {
		setTitle("Main Page");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 800, 600);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new MigLayout("", "[][grow][grow]", "[][grow]"));

		JLabel lblWhatsHot = new JLabel("Whats Hot");
		contentPane.add(lblWhatsHot, "cell 1 0");

		JLabel lblTopics = new JLabel("Topics");
		contentPane.add(lblTopics, "cell 2 0");

		String query = "Select * From Items i INNER JOIN Posts p ON i.id = p.item_id INNER JOIN Users u ON u.id = p.posted_by Where p.posted_by = "
				+ Login.LoggedInUser.Id;

		List<HashMap<String, Object>> topic = null;
		try {
			topic = Database.select(query);
		} catch (SQLException e3) {
			e3.printStackTrace();
		}

		HashMap<Integer, Double> catWeights = new HashMap<Integer, Double>();

		HashMap<Integer, Integer> catCount = new HashMap<Integer, Integer>();

		double total = 0;
		WHTopic[] topics = new WHTopic[topic.size()];
		for (int i = 0; i < topics.length; i++) {
			WHTopic temp = new WHTopic();
			temp.category = (int) topic.get(i).get("category");

			String countQuery = "select count(*) from Posts parent inner join Posts child on parent.id=child.in_reply_to INNER JOIN Users u ON u.id = parent.posted_by where parent.id="
					+ topic.get(i).get("id");
			List<HashMap<String, Object>> count = null;
			try {

				count = Database.select(countQuery);
			} catch (SQLException e1) {

				e1.printStackTrace();
			}
			int number = count.size();

			temp.comment = number;

			int numVotes = (int) topic.get(i).get("number_of_votes");

			int totalPts = (int) (topic.get(i).get("total_points"));

			temp.rating = (double) totalPts == 0 ? 1
					: numVotes / numVotes == 0 ? 1 : numVotes;
			
			temp.TopicName = topic.get(i).get("content").toString();
			temp.PostDate = (Date) topic.get(i).get("posted_date");
			temp.PostedBy = (topic.get(i).get("first_name").toString() + " " + topic.get(i).get("last_name").toString());
			topics[i] = temp;

		}

		for (WHTopic w : topics) {
			if (catCount.containsKey(w.category)) {
				int temp = catCount.get(w.category);
				catCount.put(w.category, temp++);
			}

			else {
				catCount.put(w.category, 1);
			}
			total++;
		}
		for (Integer cat : catCount.keySet()) {
			int count = catCount.get(cat);
			catWeights.put(cat, count / total);
		}

		query = "Select * From Posts p inner join Users u ON u.id = p.posted_by Where category <> 0 AND posted_date > NOW() - INTERVAL 2 WEEK AND number_of_votes > 0 LIMIT 25";

		try {
			topic = Database.select(query);
		} catch (SQLException e2) {
			e2.printStackTrace();
		}
		WHTopic[] recentTopic = new WHTopic[topic.size()];
		for (int i = 0; i < recentTopic.length; i++) {
			WHTopic temp = new WHTopic();
			temp.category = topic.get(i).get("category") == null ? 0
					: (int) topic.get(i).get("category");

			String countQuery = "select count(*) as comments from Posts parent inner join Posts child on parent.id=child.in_reply_to where parent.id="
					+ topic.get(i).get("id");
			List<HashMap<String, Object>> count = null;
			try {
				count = Database.select(countQuery);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			long number = (long) count.get(0).get("comments");

			temp.comment = number;

			temp.rating = (int) (GetRating(
					(int) topic.get(i).get("number_of_votes"),
					(int) topic.get(i).get("total_points")));
			temp.TopicName = topic.get(i).get("content").toString();
			temp.PostDate = (Date) topic.get(i).get("posted_date");
			temp.PostedBy = (topic.get(i).get("first_name").toString() + " " + topic.get(i).get("last_name").toString());
			recentTopic[i] = temp;

		}

		for (WHTopic x : recentTopic) {
			x.weight = x.comment;
			x.weight *= x.rating;
			x.weight *= (catWeights.containsKey(x.category) ? catWeights
					.get(x.category) : 0.3);
		}
		Arrays.sort(recentTopic, new Comparator<WHTopic>() {

			@Override
			public int compare(WHTopic o1, WHTopic o2) {
				return (int) (o2.weight - o1.weight);
			}
		});

		String[] columnNamesWH = { "TopicName", "Date", "PostedBy", "Rating" };

		Object[][] toAdd = new Object[recentTopic.length][4];
		for (int i = 0; i < recentTopic.length; i++) {
			toAdd[i][0] = recentTopic[i].TopicName;
			toAdd[i][1] = recentTopic[i].PostDate;
			toAdd[i][2] = recentTopic[i].PostedBy;
			toAdd[i][3] = recentTopic[i].rating;
		}

		table = new JTable(toAdd, columnNamesWH);
		JScrollPane whPane = new JScrollPane(table); 
		contentPane.add(whPane, "cell 1 1,grow");
		table.getColumn("Rating").setMaxWidth(5);
		table.getColumn("Date").setMaxWidth(75);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				JTable target = (JTable) e.getSource();
				int row = target.getSelectedRow();
				Topic topic = new Topic();
				topic.setTopicName(target.getValueAt(row, 0).toString());
				DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				java.util.Date date = null;
				try {
					date = formatter
							.parse(target.getValueAt(row, 1).toString());
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				Date sqlDate = new Date(date.getTime());
				topic.setPostDate(sqlDate);
				Topic thisTopic = Home.GetTopicByNameDate(topic);
				view_topic x = new view_topic(thisTopic);
				x.setVisible(true);
				dispose();
			}
		});

		String[] columnNamesT = { "TopicName", "Date", "PostedBy", "Rating" };
		Topic[] allTopics = Home.GetAllTopics();
		allTopicsTableObjects = new Object[allTopics.length][4];
		for (int i = 0; i < allTopics.length; i++) {
			allTopicsTableObjects[i][0] = (Object) allTopics[i].getTopicName();
			allTopicsTableObjects[i][1] = (Object) allTopics[i].getPostDate();
			allTopicsTableObjects[i][2] = (Object) allTopics[i].getPostedBy();
			allTopicsTableObjects[i][3] = (Object) ((allTopics[i]
					.getTotalPoints() == 0 ? 1 : allTopics[i].getTotalPoints()) / (allTopics[i]
					.getNumberOfVotes() == 0 ? 1 : allTopics[i]
					.getNumberOfVotes()));
		}
		

		table_1 = new JTable(allTopicsTableObjects, columnNamesT);
		JScrollPane allPane = new JScrollPane(table_1); 
		table_1.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				JTable target = (JTable) e.getSource();
				int row = target.getSelectedRow();
				Topic topic = new Topic();
				topic.setTopicName(target.getValueAt(row, 0).toString());
				DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				java.util.Date date = null;
				try {
					date = formatter
							.parse(target.getValueAt(row, 1).toString());
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				Date sqlDate = new Date(date.getTime());
				topic.setPostDate(sqlDate);
				Topic thisTopic = Home.GetTopicByNameDate(topic);
				view_topic x = new view_topic(thisTopic);
				x.setVisible(true);
				dispose();
			}
		});
		contentPane.add(allPane, "cell 2 1,grow");
		table_1.getColumn("Rating").setMaxWidth(5);
		table_1.getColumn("Date").setMaxWidth(75);

		setJMenuBar(MenuFactory.getMenu(this));

	}

	public int GetRating(int votes, int points) {
		return (points == 0 ? 1 : points) / (votes == 0 ? 1 : votes);
	}
}
